package com.rd.student.ruanjian.class4.zhangrui;

import java.util.Objects;

public class TestBank1 implements Runnable {


    // 银行类需要有账户来取钱
    // Bank has a Account  构成一个类的组合关系
    private Account1 account;
    // 取钱的金额
    private double money;

    public TestBank1(Account1 account, double money) {
        this.account = account;
        this.money = money;
    }

    @Override
    public synchronized void run() {
        // 取钱的操作
        if (account.balance < money) {
            System.out.println("余额不足");
            return;
        }

        System.out.println(Thread.currentThread().getName() + " 可以取钱");
        account.balance = account.balance - money;
        System.out.println("取钱后的余额为：" + account.balance);
    }

    public static void main(String[] args) {
        Account account = new Account("123456", 888);
        TestBank testBank = new TestBank(account, 666);
        Thread t1 = new Thread(testBank, "zhangsan");
        Thread t2 = new Thread(testBank, "lisi");

        t1.start();
        t2.start();
    }
}

// 创建一个账户类
class Account1 {
    // 属性设置为账户id和余额
    String accountId;
    double balance;

    // 创建构造器 ctrl+N
    // 选择 constructor构造器 按住shift选择两个属性 ok
    public Account1(String accountId, double balance) {
        this.accountId = accountId;
        this.balance = balance;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Account1 account = (Account1) o;
        return Objects.equals(accountId, account.accountId);
    }

    @Override
    public int hashCode() {
        return Objects.hash(accountId);
    }
}
